/**
 * 
 */
package biz.innovasoft.ndb;

import java.io.Serializable;
import java.util.List;

import biz.innovasoft.ndb.index.IndexManager;
import biz.innovasoft.ndb.index.Searcher;
import biz.innovasoft.ndb.query.Tuple;

/**
 * 
 * @author Diego Miranda
 *
 */
public class DeleteHelper implements Serializable {

	private static final long serialVersionUID = 6995664671961776157L;
	
	private GenericRepository repository;
	
	public DeleteHelper (GenericRepository repository) {
		this.repository = repository;
	}
	
	public Object delete(Long oid, boolean indexNow) throws RepositoryException {
		if (!repository.getObjects().containsKey(oid)) {
			throw new DeleteObjectException(
					"Trying to delete an object with an inexistent key. OID: "
							+ oid);
		}
		Object object = repository.getObjects().remove(oid);
		repository.availableOids.push(oid);
		if (indexNow) {
			/* Delete reference from the object index */
			IndexManager imanager = repository.getIndexManager(object.getClass());
			if (imanager == null) return object; // Return, there is no index.
			Searcher searcher = new Searcher(imanager);
			searcher.deleteIndex(oid);
			
			/* Delete reference from the root index */
			imanager = repository.getRootIndexManager(object.getClass());
			if (imanager == null) return object; // Return, there is no index.
			searcher = new Searcher(imanager);
			searcher.deleteIndex(oid);
		}
		return object;

	}
	
	public void delete (Long[] oids) throws RepositoryException {
		for (Long oid : oids) {
			delete (oid, true);
		}
	}
	
	public void delete (Class<?> clazz) {
		List<Tuple>tuples = repository.getAll(clazz);
		for (Tuple tuple : tuples) {
			delete (tuple.oid, true);
		}
		//repository.reindex(repository.getRootIndexManager(clazz));
	}

}
